<template>
  <div class="home">
    <div class="border" v-if="!dealEnd">
      <!-- 拖拽上传 -->
      <el-upload
        ref="upload"
        class="upload-demo"
        show-file-list
        action="https://jsonplaceholder.typicode.com/posts/"
        :drag="true"
        :on-change="handleChange"
        :limit="1"
        :auto-upload="false"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>
      <el-checkbox v-model="ignoreFidle">忽略外勤</el-checkbox>
      <el-button type="primary" style="margin:50px" @click="newDeal()">开始处理</el-button>
    </div>
    <div class="border table_border" v-else>
      <el-table :data="abnormalData" border max-height="680" style="width:100%">
        <!-- <el-table-column label="日期" width="140px" align="center">
          <template>{{ date }}</template>
        </el-table-column> -->
        <el-table-column prop="date" label="日期" width="140px" align="center"></el-table-column>
        <el-table-column prop="name" label="姓名" width="100px" align="center"></el-table-column>
        <el-table-column prop="time" label="考勤时间" width="100px" align="center"></el-table-column>
        <el-table-column prop="res" label="异常情况" width="90px" align="center"></el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button @click="ignoreOnce(scope.$index)" type="text" size="large">忽略本次</el-button>
            <el-button @click="ignoreStaff(scope.row)" type="text" size="large">忽略此人</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="button_line">
        <el-button type="primary" class="menu_btn" round @click="revoke">撤销</el-button>
        <el-button type="warning" class="menu_btn" round @click="handleExport">导出</el-button>
        <el-button type="info" class="menu_btn" round @click="reset">重置</el-button>
      </div>
    </div>
  </div>
</template>

<script>
// @ is an alias to /src
// import HelloWorld from "@/components/HelloWorld.vue";
import * as XLSX from 'xlsx'

export default {
  name: "AboutView",
  components: {
    // HelloWorld,
  },
  data(){
    return{
      originData: {}, // 原始表格数据
      validData: [], // 有效数据
      abnormalData: [], // 异常数据
      staffList: [], // 考勤人员列表
      times: ['08:10','11:10','13:50','16:40'], // 需要打卡的时间段
      dealEnd: false, // 是否已处理完数据
      ignoreFidle: true, // 忽略外勤异常
      showList: [], // 用于展示在表格中的数据
      ignoreList: [], // 忽略的数据 用于撤销
      ignoreIndexs: [], // 忽略的位置 用于撤销
      ignoreNumbers: [], // 上一次忽略的数量 用于撤销
      date: '', // 考勤日期 用于导出时的文件名
    }
  },
  methods: {
    handleChange(file, fileList) {
      // console.log('file ===> ', file)
      console.log('fileList ===> ', fileList)
      this.date = fileList[0].name.split('_')[2]
      // console.log('??????', this.date)
      this.readExcel({0:file.raw});
    },
    readExcel (files) { // 表格导入
      if (files.length <= 0) { // 如果没有文件名
        return false
      } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
        this.$Message.error('上传格式不正确，请上传xls或者xlsx格式')
        return false
      }
      const fileReader = new FileReader()
      fileReader.onload = (files) => {
        try {
          const data = files.target.result
          const workbook = XLSX.read(data, {
            type: 'binary'
          })
          const wsname = workbook.SheetNames[0]// 取第一张表
          console.log('wsname ----->', wsname, workbook)
          const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname], { range: 2 })// 生成json表格内容
          console.log(ws, 'ws是表格里的数据，且是json格式')
          this.originData = ws
          // 重写数据
          this.$refs.upload.value = ''
          // return ws
        } catch (e) {
          console.log(e)
          return false
        }
      }
      fileReader.readAsBinaryString(files[0])
    },
    // 新的处理方式：先根据日期分组，再调用旧的处理方式，解决一次性处理多天考勤结果的需求,旧的代码不需要重写
    newDeal() {
      const dateArray = []; // 记录全部日期
      const resData = []; // 考勤数据 根据时期分组
      const validTitle = ['正常','迟到','外勤','早退']; // 非此类数据不加入考勤数据数组
      this.originData.forEach(item => {
        const resName = item['打卡结果']
        if(validTitle.includes(resName)) {
          const date = item['考勤时间'].split(' ')[0]
          item.date = date
          const idx = dateArray.findIndex(x => x == date)
          if(idx == -1) {
            dateArray.push(date)
            resData.push([])
            const lst = dateArray.length - 1;
            resData[lst].push(item)
          } else {
            resData[idx].push(item)
          }
        }
      })
      console.log('全部日期 ->', dateArray)
      console.log('初次处理的结果 -> ', resData)
      resData.forEach(item => [
        this.deal(item)
      ])
    },
    // 处理数据
    /** 旧的处理方式：
     * 1.筛选打卡结果中，属于validTitle中的值
     * 2.将时间对应的位置插入到此人的 kqTotal中的对应位置（一天四次）
     * 3.如果是非正常结果，插入到异常列表abnormalData中（用于列表展示）
     */
    deal(dealData) {
      const validTitle = ['正常','迟到','外勤','早退'];
      let staffId = 1;
      this.staffList = []
      // 筛选有效数据 得到人员有效考勤记录的数据
      dealData.forEach(item => {
        const staffName = item['姓名']
        const resName = item['打卡结果']
        let hasStaff = this.staffList.findIndex(x => x.name == staffName);
        // 如果人员列表中没有此人，则加入
        if(hasStaff == -1) {
          this.staffList.push({id: staffId, date: item.date, name: staffName, kqTotal: ['','','','']});
          staffId += 1;
        }
        // console.log('hasStaff', hasStaff, staffName, resName);
        const lst = this.staffList.length - 1;
        if(validTitle.includes(resName)) {
          const timeNumber = this.times.findIndex(x => x == item['考勤时间'].split(' ')[1])
          this.staffList[lst].kqTotal[timeNumber] = resName;
        }
      })
      this.dealAbnormal(this.staffList);
    },
    // 根据有效数据，筛选出异常数据
    dealAbnormal(stl) {
      console.log('有效数据 -> 人员表', stl);
      stl.forEach(item => {
        item.kqTotal.forEach((kqRes, index) => {
          // 如果kqRes不是正常 并且 如果 kqRes是外勤并且没有忽略外勤的情况下 加入异常数据数组
          if(kqRes == '外勤' && this.ignoreFidle) kqRes = '正常'
          if(kqRes != '正常') {
            const abnormalItem = {
              date: item.date,
              name: item.name,
              time: this.times[index],
              res: kqRes || '缺卡'
            }
            this.abnormalData.push(abnormalItem);
          }
        })
      })
      this.$message.success('处理完成')
      this.dealEnd = true;
      console.log("异常数据：", this.abnormalData)
    },
    // 重置
    reset() {
      location.reload();
    },
    // 忽略本次异常
    ignoreOnce(index) {
      let item = this.abnormalData.splice(index, 1);
      this.ignoreIndexs.push(index)
      this.ignoreList.push(item)
      this.ignoreNumbers.push(1)
      console.log(this.ignoreList)
    },
    // 忽略此人全部异常
    ignoreStaff(row) {
      console.log(row);
      const i = this.abnormalData.findIndex(x => x.name == row.name);
      console.log('findindex => ', i);
      const number = this.abnormalData.filter(item => item.name == row.name).length;
      const datas = this.abnormalData.splice(i, number);
      this.ignoreList.push(datas);
      this.ignoreIndexs.push(i);
      this.ignoreNumbers.push(number);
    },
    // 撤销忽略
    revoke() {
      const i = this.ignoreIndexs.pop();
      const item = this.ignoreList.pop();
      const number = item.length;
      let a = 0;
      while(a < number) {
        this.abnormalData.splice(i+a, 0, item[a]);
        console.log(item[a])
        a++
      }
    },
    handleExport() {
      let data = []
      this.abnormalData.forEach(item => {
        const e = {
          '日期': item.date,
          '姓名': item.name,
          '考勤时间': item.time,
          '异常情况': item.res
        }
        data.push(e)
      })
      console.log('导出：',data);
      this.exportToExcel(data, this.date);
    },
    exportToExcel(data, fileName) {
      // 导出
      // 将数据转换为工作表
      const worksheet = XLSX.utils.json_to_sheet(data);
      // 创建工作簿并添加工作表
      const workbook = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");
      // 生成Excel文件
      const excelBuffer = XLSX.write(workbook, {
        bookType: "xlsx",
        type: "array",
      });
      // 创建Blob对象
      const dataBlob = new Blob([excelBuffer], {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8",
      });
      // 创建链接并模拟点击下载
      const downloadLink = document.createElement("a");
      downloadLink.href = window.URL.createObjectURL(dataBlob);
      downloadLink.download = fileName;
      document.body.appendChild(downloadLink);
      downloadLink.click();
      document.body.removeChild(downloadLink);
    },
  }
};
</script>
<style lang="less" scoped>
.border{
  margin: 10px auto;
  text-align: center;
  padding: 50px 20px 0 20px;
}
.menu_btn{
  margin-right: 30px;
}
.table_border {
  width: 640px;
  margin: 0 auto;
}
.button_line {
  margin-top: 30px
}
</style>